const {
  querySql,
  queryOne,
  updateSql,
  insertSql,
  deleteManySql,
} = require("../db");

function login(cardId, password) {
  return querySql(
    `select * from user_data where cardId = ${cardId} and password = '${password}'`
  );
}

function getUserInfo(cardId) {
  return queryOne(`select * from user_data where cardId = '${cardId}'`);
}

function getUserList(query) {
  const { state, cardId, userName, pageNum, pageSize, roleId } = query;
  return querySql(
    `select * from user_data where ${state ? `state = ${state}` : ""} ${
      cardId ? `and cardId = ${cardId}` : ""
    } ${userName ? `and userName like '%${userName}%'` : ""} ${
      roleId ? `and roleId = ${roleId}` : ""
    } limit ${(pageNum - 1) * pageSize}, ${pageSize}`
  );
}

function getUserListByNameOrCardId(searchValue) {
  return querySql(
    `select userName , cardId , id from user_data where userName like '%${searchValue}%' or cardId like '%${searchValue}%' limit 10`
  );
}

function getUserInfoById(id) {
  return queryOne(
    `select id , userName , cardId  from user_data where id = ${id}`
  );
}

function getTotalCount(query) {
  const { state, cardId, userName } = query;
  return queryOne(
    `select count(*) as totalCount from user_data where ${
      state ? `state = ${state}` : ""
    } ${cardId ? `and cardId = ${cardId}` : ""} ${
      userName ? `and userName like '%${userName}%'` : ""
    }`
  );
}

function editUser(query) {
  return updateSql(query, "user_data", `where id = ${query.id}`);
}

function createUser(query) {
  query.createTime = new Date();
  return insertSql(query, "user_data");
}

function deleteUser(userIds) {
  return deleteManySql("id", userIds, "user_data");
}

function allUser() {
  return querySql(`SELECT * FROM user_data`);
}

module.exports = {
  login,
  getUserInfo,
  getUserList,
  getTotalCount,
  editUser,
  createUser,
  deleteUser,
  getUserListByNameOrCardId,
  getUserInfoById,
  allUser,
};
